<template>
  <div class="glossary-container">
    <a-alert type="info" message="术语表中的内容会保持原样输出，不会被翻译" banner class="mb-3" />
    <div v-for="(item, index) in glossary" :key="index" class="glossary-item">
      <a-input-group compact>
        <a-input
          v-model:value="item.source"
          placeholder="原文（如：AI助手）"
          :style="{ width: '48%' }"
        />
        <a-input
          v-model:value="item.target"
          placeholder="译文（如：AI Assistant）"
          :style="{ width: '48%' }"
        />
        <a-button type="danger" size="small" @click="removeTerm(index)" style="width: 4%">
          <MinusOutlined />
        </a-button>
      </a-input-group>
    </div>

    <a-button block @click="addTerm" class="mt-2"> <PlusOutlined /> 添加术语 </a-button>

    <div class="glossary-footer mt-4">
      <a-button @click="cancel" class="mr-2">取消</a-button>
      <a-button type="primary" @click="saveGlossary">保存</a-button>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { message } from 'ant-design-vue'
import Http from '@/api/http'

const emit = defineEmits(['close'])

const glossary = ref([
  { source: '智能体', target: 'Agent' },
  { source: '大模型', target: 'LLM' }
])

const cancel = () => {
  emit('close')
}

// 添加术语
const addTerm = () => {
  glossary.value.push({ source: '', target: '' })
}

// 删除术语
const removeTerm = (index) => {
  if (glossary.value.length > 1) {
    glossary.value.splice(index, 1)
  } else {
    message.warning('至少保留一个术语项')
  }
}

// 保存术语表
const saveGlossary = () => {
  // 校验：每项的 source 和 target 都不能为空
  const invalidItem = glossary.value.find((item) => !item.source?.trim() || !item.target?.trim())
  if (invalidItem) {
    message.warning('请填写完整的术语（原文和译文）')
    return
  }

  Http.post('/api/term/saveBatch', glossary.value).then((res) => {
    message.success('术语表已保存')
    // 通知父组件关闭抽屉（通过 emit）
    emit('close')
  })
}

function getAll() {
  Http.get('/api/term/getAll').then((res) => {
    if (res.data && res.data.length > 0) {
      glossary.value = res.data
    }
  })
}

onMounted(() => {
  getAll()
})
</script>

<style scoped>
.glossary-item {
  margin-bottom: 8px;
}

.glossary-footer {
  text-align: right;
}

.mb-3 {
  margin-bottom: 12px;
}
.mt-2 {
  margin-top: 8px;
}
.mt-4 {
  margin-top: 16px;
}
.mr-2 {
  margin-right: 8px;
}
</style>
